package com.itheima.task;

import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

import static com.itheima.common.constant.RedisConstant.SETMEAL_PIC_DB_RESOURCES;
import static com.itheima.common.constant.RedisConstant.SETMEAL_PIC_RESOURCES;

/**
 * 定时清理垃圾图片的任务
 */
@Slf4j
@Component
public class ImageCleanupTask {


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * qingli
     */
//    @Scheduled(initialDelay = 60 * 1000, fixedDelay = Long.MAX_VALUE)//一分钟后触发一次，用于测试
    @Scheduled(cron="0 0 10,14,16 * * ?")//每天10、14、16触发一次
    public void cleanUpUnusedImages() {
        log.info("开始执行垃圾图片清理任务");

        try {
            //获取所有上传的图片集合
            Set<String> uploadedImages = redisTemplate.opsForSet().members(SETMEAL_PIC_RESOURCES);

            //获取所有已使用的图片集合
            Set<String> usedImages = redisTemplate.opsForSet().members(SETMEAL_PIC_DB_RESOURCES);

            if (uploadedImages == null || uploadedImages.isEmpty()) {
                log.info("没有需要清理的垃圾图片");
                return;
            }

            //计算差值，得到未使用的垃圾图片
            uploadedImages.removeAll(usedImages);

            if (uploadedImages.isEmpty()) {
                log.info("没有需要清理的垃圾图片");
                return;
            }

            log.info("发现 {} 张垃圾图片需要清理", uploadedImages.size());

            //遍历并删除垃圾图片
            for (String imageName : uploadedImages) {
                try {
                    //从OSS删除图片
                    aliOssUtil.delete(imageName);
                    log.info("成功删除垃圾图片: {}", imageName);

                    //从上传集合中移除已删除的图片
                    redisTemplate.opsForSet().remove(SETMEAL_PIC_RESOURCES, imageName);
                } catch (Exception e) {
                    log.error("删除垃圾图片 {} 失败: {}", imageName, e.getMessage());
                }
            }

            log.info("垃圾图片清理任务执行完毕");
        } catch (Exception e) {
            log.error("执行垃圾图片清理任务时发生错误", e);
        }
    }
}